#!/bin/bash

set -e

FILE_LIST=./help
FILE_README=./README.md
DIR_EN=./en
DIR_CN=./cn

function check_file() {
    if [ ! -f ${FILE_LIST} ]; then
        echo -e "file list is not exist."
        return 1
    fi
    dos2unix ${FILE_LIST}

    if [ ! -f ${FILE_README} ]; then
        touch ${FILE_README}
        dos2unix ${FILE_README}
    fi

    if [ -d ${DIR_EN} ]; then
        rm -rf ${DIR_EN}
    fi
    mkdir -p ${DIR_EN}

    if [ -d ${DIR_CN} ]; then
        rm -rf ${DIR_CN}
    fi
    mkdir -p ${DIR_CN}
}

function write_readme() {
    local title=$1
    local cmd=$2
    echo "" >> ${FILE_README}
    echo "### ${title} gn help ${cmd}" >> ${FILE_README}
    echo "" >> ${FILE_README}
    echo "- [英文](./en/${cmd}.md)" >> ${FILE_README}
    echo "- [中文](./cn/${cmd}.md)" >> ${FILE_README}
    echo "- 状态：todo" >> ${FILE_README}
}

function write_en() {
    local cmd=$1
    echo "### gn help ${cmd}" > ${DIR_EN}/${cmd}.md
    bash -c "gn help --markdown ${cmd}" >> ${DIR_EN}/${cmd}.md
}

function create_cn() {
    local cmd=$1
    echo "### gn help ${cmd}" > ${DIR_CN}/${cmd}.md
    bash -c "gn help --markdown ${cmd}" >> ${DIR_CN}/${cmd}.md
}

function main() {
    set +e
    check_file
    if [[ $? -ne 0 ]]; then
        return 0
    fi
    set -e

    local idx=1
    while read cmd; do
        set +e
        $(gn help ${cmd} > /dev/null 2>&1)
        if [[ $? -ne 0 ]]; then
            echo "gn help ${cmd} is not exist"
            set -e
            continue
        fi
        set -e

        if [ ${cmd} ]; then
            local title=2.${idx}
            write_readme ${title} ${cmd}
            write_en ${cmd}
            create_cn ${cmd}
            let idx++
        fi
    done < ${FILE_LIST}
}

main
